package com.appbee.songs.client.presenter.impl;

import java.util.ArrayList;

import com.appbee.core.client.jsni.JsArrayConverter;
import com.appbee.gdata.youtube.client.model.SimpleEntry;
import com.appbee.songs.client.presenter.ISongSelectionPresenter;
import com.appbee.songs.client.ui.IYoutubePlayerView;
import com.appbee.songs.shared.SongProxy;
import com.google.gwt.core.client.JsArray;

public class ShowYoutubePlayerSongSelectionPresenter implements ISongSelectionPresenter
{
	private boolean playerPanelShowing = false;
	private IYoutubePlayerView view;

	public void setView(IYoutubePlayerView view)
	{
		this.view = view;
		view.setSongsSelectionPresenter(this);
	}

	@Override
	public void onSelectionChange(SongProxy selectedSong)
	{
		if (selectedSong == null)
		{
			if (playerPanelShowing)
			{
				playerPanelShowing = false;
				view.setPlayerPanelShowing(playerPanelShowing);
			}
			view.setLyrics("");
		}
		else
		{
			if (!playerPanelShowing)
			{
				playerPanelShowing = true;
				view.setPlayerPanelShowing(playerPanelShowing);
			}
			if (selectedSong.getYoutubeData() != null)
			{
				JsArray<SimpleEntry> jsArray = SimpleEntry.parseJson("v="
						+ selectedSong.getYoutubeData());
				view.setTubeListData(JsArrayConverter.toList(jsArray));
				if (jsArray.length() > 0)
				{
					view.setSelectedTube(jsArray.get(0));
				}
				else
				{
					view.clearPlayer();
				}
			}
			else
			{
				view.setTubeListData(new ArrayList<SimpleEntry>());
				view.clearPlayer();
			}
			view.setLyrics(selectedSong.getLyrics());
		}
	}

}
